import axios from 'axios'
import { useAppStore } from '@/store/modules/app'
import { PATH_URL } from '@/config/axios/service'
import request from '@/config/axios'
//导入
export const uploadExcelApi = (file: File, url: string): Promise<any> => {
  const appStore = useAppStore()
  const formData = new FormData()
  formData.append('file', file)
  return axios({
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data',
      'x-access-token': appStore.token
    },
    url: PATH_URL + url,
    data: formData
  })
}
//导出 /sys/dict/exportXls  resType:'application/json'|'blob'
export const dictExportXlsAll = (url, type, data, responseType): Promise<exportResponse> => {
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  const obj = {
    url,
    data,
    headers,
    responseType
  }
  if (!responseType) {
    delete obj.responseType
  }
  return request[type](obj)
}
//下载导出方法 blob格式
export const downXls = async (res, xlsName, url) => {
  if (url) {
    const a = document.createElement('a') //创建一个a标签元素
    a.style.display = 'none' //设置元素不可见
    a.href = url //设置下载地址
    document.body.appendChild(a) //加入
    a.click()
    document.body.removeChild(a) //释放
  } else {
    const date = new Date()
    const time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    const blob = new Blob([res.data], {
      type: 'application/octet-stream'
    })
    // xlsName 导出名字
    const filename = xlsName + time + '.xls'
    // 将blob对象转为一个URL
    const blobURL = window.URL.createObjectURL(blob)
    // 创建一个a标签
    const tempLink = document.createElement('a')
    // 隐藏a标签
    tempLink.style.display = 'none'
    // 设置a标签的href属性为blob对象转化的URL
    tempLink.href = blobURL
    // 给a标签添加下载属性
    tempLink.setAttribute('download', filename)
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 将a标签添加到body当中
    document.body.appendChild(tempLink)
    // 启动下载
    tempLink.click()
    // 下载完毕删除a标签
    document.body.removeChild(tempLink)
    window.URL.revokeObjectURL(blobURL)
  }
}
